/*
Package middlewares
@Author   : Uyynot
@Email    : uyynot@qq.com
@Time     : 2024/3/27 14:16
@File     : auth_jwt.go
@Project  : gohub
@Desc     :
*/
package middlewares

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gohub/app/models/user"
	"gohub/pkg/config"
	"gohub/pkg/jwt"
	"gohub/pkg/response"
)

/**
 * AuthJWT
 * @Description: jwt用户认证中间件
 * @return gin.HandlerFunc
 */
func AuthJWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		//从表头 Authorization:Bearer XXXXX中获取信息，并验证jwt的准确性
		claims, err := jwt.NewJWT().ParserToken(c)

		//jwt解析失败
		if err != nil {
			response.Unauthorized(c, fmt.Sprintf("请查看 %v 相关的接口认证文档", config.GetString("app.name")))
			return
		}
		//jwt解析成功
		userModel := user.Get(claims.UserID)
		if userModel.ID == 0 {
			response.Unauthorized(c, "不存在的用户")
			return
		}

		//将用户信息存入gin.context中，后序auth包将从这里拿到当前用户数据
		c.Set("current_user_id", userModel.GetStringID())
		c.Set("current_user_name", userModel.Name)
		c.Set("current_user", userModel)

		c.Next()
	}
}
